﻿namespace Paw.Services.Infrastructure
{
    using System;
    using System.Globalization;
    using System.Security.Cryptography.X509Certificates;

    public class CertificateUtil
    {
        public static X509Certificate2 GetCertificate(StoreName name, StoreLocation location, string thumbprint)
        {

            // Get the certificate store for the current user.
            X509Store stored = new X509Store(name, location);
            X509CertificateCollection certs = null;
            stored.Open(OpenFlags.ReadOnly);

            try
            {
                X509Certificate2 res = null;
                // new Certificate Collection
                certs = stored.Certificates;
                foreach(X509Certificate2 cert in certs)
                {
                    if (cert.Thumbprint.Equals(thumbprint, StringComparison.OrdinalIgnoreCase))
                    {
                        res = new X509Certificate2(cert);
                        break;
                    }

                }

                    if (res == null)
                    {
                        throw new ApplicationException(string.Format(CultureInfo.InvariantCulture, "No Certificate found {0}", thumbprint));
                    }

                    return res;
                
            }

            finally 
            {
                if (certs != null)
                {
                    foreach(X509Certificate2 cert in certs)
                    {
                        cert.Reset();
                    }
                }

                stored.Close();
            }
         }
    }
}